package com.wen.controller;

import com.google.code.kaptcha.Producer;
import com.wen.pojo.Auth;
import com.wen.pojo.CurrentUser;
import com.wen.pojo.LoginUser;
import com.wen.pojo.User;
import com.wen.service.AuthService;
import com.wen.service.UserService;
import com.wen.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    //注入
    @Autowired
    private Producer producer;

    @Autowired
    private UserService userService;
    //注入redis
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //获取验证码
    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response) throws IOException {
        //生成验证码图片的文本
        String text = producer.createText();
        //使用文本生成图片
        BufferedImage image = producer.createImage(text);
        //将验证码文本作为键存入redis,设置过期时间5分钟
        stringRedisTemplate.opsForValue().set("login:yzm:"+text,text,5,TimeUnit.MINUTES);

        //将验证码图片响应给前端
        //设置响应正文image/jpeg
        response.setContentType("image/jpeg");
        //写给前端
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image,"jpg",out);
        //刷新
        out.flush();
    }

     //登录
    @PostMapping("/login")
    public Result login (@RequestBody LoginUser loginUser){
        String code = stringRedisTemplate.opsForValue().get("login:yzm:" + loginUser.getVerificationCode());
        if(code == null) return Result.fail(1,"验证码错误");
        User user = userService.findUserByCode(loginUser.getUserCode());
        if(user == null) return Result.fail(1,"账号不存在");
        if(user.getUserState().equals("0")) return Result.fail(1,"用户未审核");
        String pwd = Md5Util.getMD5String(loginUser.getUserPwd());
        if(user.getUserPwd().equals(pwd)){
            //存入token
            String token = JwtUtil.genToken(new CurrentUser(user.getUserId(), user.getUserCode(), user.getUserName()));
            stringRedisTemplate.opsForValue().set("login:token:"+token,token,12,TimeUnit.HOURS);
            return Result.ok(200,"登录成功",token);
        }else{
            return Result.fail(1,"用户密码不正确");
        }
    }

    //获取登录用户信息
    @GetMapping("/curr-user")
    public Result currUser(){
        CurrentUser currentUser = ThreadLocalUtil.get();
        return Result.ok(200,"获取成功",currentUser);
    }

    //加载用户权限
    @Autowired
    private AuthService authService;
    @GetMapping("/user/auth-list")
    public Result authList(){
        CurrentUser currentUser = ThreadLocalUtil.get();
        int userId = currentUser.getUserId();
        List<Auth> authList = authService.authTreeByUid(userId);
        return Result.ok(200,"获取成功",authList);
    }

    @RequestMapping ("/logout")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("Token");
        stringRedisTemplate.delete("login:token:"+token);
        ThreadLocalUtil.remove();
        return Result.ok(200,"退出登录",null);
    }

}
